package com.zhiyou100.crm.servlet.role;

import java.io.IOException;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zhiyou100.crm.pojo.AdminBaseServlet;
import com.zhiyou100.crm.pojo.Role;
import com.zhiyou100.crm.service.RoleService;
import com.zhiyou100.crm.service.impl.RoleServiceImpl;
/**
 * 更新角色
 */
@WebServlet("/role/update")
public class UpdateServlet extends AdminBaseServlet {
	private static final long serialVersionUID = 1L;
	RoleService roleService=new RoleServiceImpl();
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		String id=request.getParameter("id");
		int roleId = Integer.parseInt(id);
		request.getSession().setAttribute("id",id);
		List<Role> roles=roleService.queryRole();
		Role role=new Role();
		for (int i = 0; i <roles.size(); i++) {
			int role_id = roles.get(i).getRole_id();
			if(roleId==role_id){
				role=roles.get(i);
				request.setAttribute("role",role);
				break;
			}
		}
		if(role!=null) {
			request.getRequestDispatcher("/WEB-INF/view/role/update.jsp").forward(request, response);
		}else{
			response.sendRedirect(request.getContextPath()+"/list.jsp");
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		int roleId= Integer.parseInt(((String)request.getSession().getAttribute("id")));
		String roleName=request.getParameter("roleName");
		String roleDesc = request.getParameter("roleDesc");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long l = System.currentTimeMillis();
		String format = df.format(new Date(l));
		Timestamp time=Timestamp.valueOf(format);
		Role role=new Role(roleId,roleName,roleDesc,time);
		int a=roleService.update(role);
		if(a>0) {
			System.out.println("成功");
			response.sendRedirect(request.getContextPath()+"/role/list");
		}else{
			System.out.println("失败");
			response.sendRedirect(request.getContextPath()+"/WEB-INF/view/role/update.jsp");
		}
	}

}
